package personal.vap.route.tracker.server;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

public class RouteManager {

  private Map<String, Route> routes = new HashMap<String, Route>();
  
  private static RouteManager INSTANCE = new RouteManager();
  
  public static RouteManager getInstance() {
    return INSTANCE;
  }
  
  private synchronized Iterator<Route> getRoutes() {
    return routes.values().iterator(); 
  }
  
  public synchronized void addRoute(Route route) {
    routes.put(route.name, route);
  }
  
  private synchronized Set<String> getRouteNames() {
    return routes.keySet();
  }
  
  private synchronized Route getRouteByName(String name) {
    return routes.get(name);
  }
  
  public RESTResponse getRouteDetailsResponse(String routeName) throws ErrorResponseException {
    Route route = getRouteByName(routeName);
    if (route == null) {
      throw new ErrorResponseException(404, "Route does not exist");
    }
    RouteDetailsResponse response = new RouteDetailsResponse();
    response.message = "Details for route " + routeName;
    response.statusCode = HttpServletResponse.SC_OK;
    response.routeDetails = route;
    return response;
  }

  public RESTResponse getListCommandResponse() throws ErrorResponseException {
    Set<String> routeNames = getRouteNames();
    RouteListResponse restResponse = new RouteListResponse();
    restResponse.statusCode = HttpServletResponse.SC_OK;
    restResponse.routeNames = routeNames;
    return restResponse;
  }


}
